package com.controller;

import com.address.Book;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.utils.R;
import com.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author arthorn
 * @create 2022-05-17-9:38
 */
@RestController
@RequestMapping("/cart")
public class ShoppingCartController {
    @Autowired
    private ICartService CartServiceImpl;

    //添加商品到购物车
    @PostMapping
    public R saveOder(@RequestBody Book book)throws Exception{
        if(book.getName().equalsIgnoreCase("共产")){
            throw new Exception();
        }
        boolean flag = CartServiceImpl.save(book);
        return new R(flag,flag?"添加成功^_^!":"添加失败-_-!",flag?+1:+1-1);
    }

    //从购物车中删除商品
    @DeleteMapping("{id}/{howmany}")
    public R delete(@PathVariable Integer id,@PathVariable Integer howmany){
        boolean flag = CartServiceImpl.removeById(id);
        return new R(flag,flag?"删除成功^_^!":"删除失败-_-!",flag?howmany-1:+1-1);
    }

    //模糊分页查找商品
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,Book book){
        IPage<Object> page = CartServiceImpl.getPage(currentPage, pageSize,book);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if( currentPage > page.getPages()){
            page = CartServiceImpl.getPage((int)page.getPages(), pageSize,book);
        }
        return new R(true, page);
    }

    //将确定购买商品提交到订单界面
    @PostMapping("addgoods")
    public R addGoods(Book[] books){
        return new R(true,books);
    }
}